package com.candy.weixin.mp.handler;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.candy.weixin.mp.builder.TextBuilder;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
public class MsgHandler extends AbstractHandler {

    @Resource
    private RedisTemplate redisTemplate;

    public final static String LoginRandomUserPrefix = "login:random:user:";

    enum MessageContent
    {
        LONGIN("0","登录"),
        OPENID("9","获取用户微信标识");

        /**
         * 消息内容
         */
        private String content;
        /**
         * 消息描述
         */
        private String description;

        MessageContent(String content, String description)
        {
            this.content=content;
            this.description=description;
        }

        public String getContent()
        {
            return content;
        }

        public String getDescription()
        {
            return description;
        }
    };

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) {

        if (!wxMessage.getMsgType().equals(XmlMsgType.EVENT)) {
            //TODO 可以选择将消息保存到本地
        }

        //当用户输入关键词如“你好”，“客服”等，并且有客服在线时，把消息转发给在线客服
        try {
            if (StringUtils.startsWithAny(wxMessage.getContent(), "你好", "客服")
                && weixinService.getKefuService().kfOnlineList()
                .getKfOnlineList().size() > 0) {
                return WxMpXmlOutMessage.TRANSFER_CUSTOMER_SERVICE()
                    .fromUser(wxMessage.getToUser())
                    .toUser(wxMessage.getFromUser()).build();
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        String content;
        // 组装回复消息
        if(MessageContent.LONGIN.getContent().equals(wxMessage.getContent()) || "验证码".equals(wxMessage.getContent()))
        {
            String number = RandomUtil.randomNumbers(7);
            while(redisTemplate.hasKey(LoginRandomUserPrefix + number))
            {
                number = RandomUtil.randomNumbers(7);
            }
            redisTemplate.opsForValue().set(LoginRandomUserPrefix + number, wxMessage.getFromUser(),1L, TimeUnit.MINUTES);
            content = "欢迎使用【<a href=\"http://cvsea.com\">Candy敏捷开发框架</a>】\n您正在使用微信验证码登录，有效期1分钟，请勿泄漏。\n【Candy】验证码："+number+"\n"+ DateUtil.now();
        }
        else if(MessageContent.OPENID.getContent().equals(wxMessage.getContent()))
        {
            content = "【Candy】您的微信标识："+wxMessage.getFromUser()+"，请发送给系统管理员，进行账号绑定。";
        }
        else
        {
            content=SubscribeHandler.getHelpMessage();
        }
        return new TextBuilder().build(content, wxMessage, weixinService);
    }

}
